<template>
  <view>
    <view style="position: relative;top: -20rpx">
      <uni-section type="line" title="图文相关">
      </uni-section>
      <view style="margin: 0 20rpx">
        <u--form labelPosition="left" :model="activity" labelWidth="auto">
          <u-form-item label="活动标题 : " borderBottom>
            <u--textarea
                v-model="activity.title"
                placeholder="输入活动标题"
                clearable
                autoHeight
                border="none"
                maxlength="30"
                count="true"
            >
            </u--textarea>
          </u-form-item>

          <u-form-item label="背景图像 : " borderBottom>
            <uni-file-picker
                ref="bannerFile"
                fileMediatype="image"
                mode="grid"
                @select="activity.banner.select"
                @delete="activity.banner.delete"
                :image-styles="upload.style"
                limit="1"
                v-model="activity.banner.list"
            >
              <u-icon name="photo" color="#42535f" size="40"></u-icon>
            </uni-file-picker>
          </u-form-item>

          <u-form-item label="活动简介  :" borderBottom>
            <u--textarea
                v-model="activity.overview"
                placeholder="输入活动简介"
                clearable
                autoHeight
                border="none"
                maxlength="255"
                count="true"
            >
            </u--textarea>
          </u-form-item>

          <u-form-item label="活动详情(图文并茂) " borderBottom>
            <u-button
                type="success"
                shape="circle"
                plain
                text="打开编辑窗"
                @click="editor.open"
            >
            </u-button>
          </u-form-item>
        </u--form>
      </view>

      <uni-section type="line" title="营销相关">
      </uni-section>
      <view style="margin: 0 20rpx">
        <u--form labelPosition="left" :model="activity" labelWidth="auto">
          <u-form-item label="活动时间 :" borderBottom>
            <uni-datetime-picker
                :hide-second=true
                type="datetimerange"
                v-model="activity.time.value"
                @change="activity.time.change"
                rangeSeparator="至"/>
          </u-form-item>

          <u-form-item label="活动地址 :" borderBottom>
            <view style="margin: 10px 0">
              <u--textarea
                  v-model="activity.location.text"
                  autoHeight
                  disabled
                  border="surround"
              >
              </u--textarea>
            </view>
            <u-button type="success" shape="circle" plain @click="activity.location.openMap()">
              点击定位活动地址
            </u-button>
          </u-form-item>

          <u-form-item label="支持报名人数(-1为无限) :" borderBottom>
            <u-number-box
                v-model="activity.registerCount"
                :step="1"
                :min="-1"
                :max="999999"
                bgColor="#ffffff"
                inputWidth="80px"
            >
            </u-number-box>
          </u-form-item>

          <u-form-item label="是否收费 :" borderBottom>
            <u-switch
                v-model="activity.hasCost"
                :activeValue=1
                :inactiveValue=0
            >
            </u-switch>
          </u-form-item>

          <u-form-item v-if="activity.hasCost === 1" label="报名费用(单位/元,支持两位小数) :" borderBottom>
            <u--input
                v-model="activity.cost"
                type="digit"
                placeholder="报名费用"
            >
            </u--input>
          </u-form-item>
        </u--form>
      </view>

      <view>
        <view style="margin: 10px">
          <u-button type="primary" shape="circle" @click="commit">
            <text style="font-size: 18px;font-weight: bold">提 交</text>
          </u-button>
        </view>
      </view>
    </view>

    <!--自己封装的提示器-->
    <popup ref="popup"/>

    <!--富文本-->
    <view>
      <uni-drawer ref="showEditor" mode="left" width="410" :maskClick=false>
        <view>
          <robin-editor
              ref="editor"
              class="editor"
              v-model="editor.context"
              muiltImage="true"
              compressImage="false"
              :imageUploader="editorUploadImg"
              @cancel="editor.cancel"
              @save="editor.save"
              @setUrlId="setUrlId">
          </robin-editor>
        </view>
      </uni-drawer>
    </view>

  </view>
</template>

<script>
import service from "@/utils/service";
import {pathToBase64} from "@/js_sdk/mmmm-image-tools";
import popup from "@/merchant/my/my-popup"

export default {
  components: {
    popup
  },
  data() {
    let _vm = this;
    return {
      target: 'add',
      /* 文件上传相关对象 */
      upload: {
        style: {
          "height": 80, // 边框高度
          "width": 80, // 边框宽度
          "border": { // 如果为 Boolean 值，可以控制边框显示与否
            "color": "#3646505e", // 边框颜色
            "width": "3px", // 边框宽度
            "style": "solid", // 边框样式
          },
        },
      },
      activity: {
        /* 活动ID */
        id: '',
        /* 活动标题 */
        title: '',
        /* 活动背景图 */
        banner: {
          list: [],
          def() {
            this.list = [];
          },
          // 选中图像
          select(e) {
            let _t = this;
            let banner = _vm.activity.banner;
            console.log('选中活动背景图 ：', e);
            let size = 10;
            if (service.check.fileSizeOutBounds(e.tempFiles, size)) {
              _vm.$refs.popup.error('不能上传超过 ' + size + ' M 的图像')
              // 清空
              _vm.$refs.bannerFile.clearFiles(0);
              banner.def();
              return
            }
            pathToBase64(e.tempFilePaths[0]).then(res => {
              banner.list.push({
                url: e.tempFilePaths[0],
                base64: res
              });
            });
          },
          // 删除选中头像
          delete(e) {
            console.log("删除活动背景图 :", e)
            _vm.activity.banner.def();
          }
        },
        /* 活动简介 */
        overview: '',
        /* 活动详情 富文本 */
        content: '',
        /* 活动时间 */
        time: {
          /*0 开始时间 1 结束时间*/
          value: [],
          change(e) {
            console.log("选择活动时间 : ", e)
          }
        },

        /* 活动地址 */
        location: {
          /*文本内容*/
          text: '',
          /*纬度*/
          lat: '',
          /*经度*/
          lng: '',
          /* 参数纬度 */
          cacheLat: '',
          /* 缓存经度 */
          cacheLng: '',
          /* 打开地图选择自提地址 */
          openMap() {
            uni.chooseLocation({
              latitude: _vm.activity.location.cacheLat,
              longitude: _vm.activity.location.cacheLng,
              success: res => {
                console.log("自提地址选中 : ", res)
                if (service.check.isNull(res.address)) {
                  _vm.$refs.popup.error("请定位后选择下方中其中一个地址点击确定,进行有效定位")
                  return
                }
                _vm.activity.location.text = res.address;
                _vm.activity.location.lat = res.latitude;
                _vm.activity.location.lng = res.longitude;
                _vm.activity.location.cacheLat = res.latitude;
                _vm.activity.location.cacheLng = res.longitude;
              }
            })
          }
        },

        /* 最大报名人数 */
        registerCount: -1,

        /* 是否收费 0 免费 1收费 */
        hasCost: 0,

        /* 活动报名费用 */
        cost: 1.00,
        /* 静态资源id */
        urlId: ''
      },
      /* 富文本对象 */
      editor: {
        // 空文本展位
        placeholder: '请输入商品详情',
        // 富文本内容
        context: '',
        // 富文本临时内容
        tempText: '',
        // 初始值
        initial: "<p><br></p>",
        open() {
          this.$refs.showEditor.open()
        },
        save(e) {
          console.log("富文本保存事件 : ", e)
          // 如果跟初始值一致则不进行赋值
          if (e.html !== _vm.editor.initial) {
            _vm.editor.context = service.copy(e.html)
            _vm.activity.content = service.copy(e.html)
          }
          _vm.editor.close();
        },
        // 取消则测回修改
        cancel(e) {
          _vm.editor.close();
        },
        close() {
          _vm.$refs.showEditor.close()
        },
      },
      /* 加载对象 */
      loading: {
        // 进度
        plan: 0,
        // 阈值
        threshold: 0,
        step() {
          if (++this.plan >= this.threshold) {
            uni.hideLoading();
          }
        }
      },
    }
  },
  methods: {
    /*设置资源路径id*/
    setUrlId(v) {
      this.activity.urlId = v;
    },
    /* 富文本上传图像 */
    editorUploadImg(path, callback, _t = this) {
      // 获取图像地址前缀
      let imgApi = this.$reqConfig.URLIMAGE
      // 获取请求头类型
      this.contentType = this.$reqConfig.CONTENTTYPE + ";+charset=UTF-8"
      // 获取token
      this.token = uni.getStorageSync("merchantsToken").token
      uni.uploadFile({
        url: this.$reqConfig.UPLOADAPI + 'merchant/merchantGroupGoods/uploadImg',
        filePath: path,
        name: 'file',
        header: {
          "Authorization": this.token,
          "Content-type": this.contentType,
          "type": "merchantsToken"
        },
        success: res => {
          let result = JSON.parse(res.data);
          if (result.code === 0) {
            callback(imgApi + result.result.uploads[0])
            this.$emit('setUrlId', result.result.id)
          }
        },
      })
    },
    commit() {
      if (this.checkParam()) {
        return;
      }
      let _t = this;
      let requestParam = _t.getRequestParam();
      uni.showLoading({
        title: '提交信息中...',
        mask: true
      })
      this.$axios({
        url: 'merchant/merchantActivity/add',
        method: 'post',
        data: requestParam,
        header: {
          "Authorization": this.token,
          "Content-type": this.contentType,
          "type": "merchantsToken"
        },
      }).then(res => {
        console.log(" merchant/merchantActivity/add :  ", res)
        if (res.code === 0) {
          _t.$refs.popup.success('提交信息成功 : ' + res.message)
          uni.navigateBack({
            delta: 1
          })
        } else {
          _t.$refs.popup.error(' 提交信息失败 :  ' + res.message)
        }
      }).finally(() => {
        uni.hideLoading();
      })
    },
    getDetail() {
      let _t = this;
      this.$axios({
        url: 'merchant/merchantActivity/detail',
        method: "post",
        data: {
          id: _t.activity.id
        },
        header: {
          "Authorization": this.token,
          "Content-type": this.contentType,
          "type": "merchantsToken"
        },
      }).then(res => {
        console.log(" merchant/merchantActivity/detail :  ", res)
        if (res.code === 0) {
          let errorFields = [];

          service.executeTask(function () {
            _t.activity.title = res.result.title;
          },errorFields,"活动标题")

          service.executeTask(function () {
            _t.activity.banner.list.push({url: _t.imgApi + res.result.banner, base64: ''});
          },errorFields,"北京图像")

          service.executeTask(function () {
            _t.activity.overview = res.result.overview;
          },errorFields,"活动简介")

          service.executeTask(function () {
            if(!res.result.content.includes("style")){
              _t.activity.content = res.result.content.replaceAll(/\<img/gi,
                  '<img style="max-width:100%;height:auto"');
            }
            if(!res.result.content.includes(_t.imgApi)){
              _t.activity.content = res.result.content.replaceAll(/src="/gi, 'src=' + '\"' + _t.imgApi);
            }
            _t.editor.context = _t.activity.content;
          },errorFields,"活动详情")

          service.executeTask(function () {
            _t.activity.time.value.push(service.style.time(res.result.openTime,6)
                ,service.style.time(res.result.overTime,6));
          },errorFields,"活动时间")

          service.executeTask(function () {
            _t.activity.location.text = res.result.address;
            _t.activity.location.lat = res.result.lat;
            _t.activity.location.lng = res.result.lng;
            _t.activity.location.cacheLat = res.result.lat;
            _t.activity.location.cacheLng = res.result.lng;
          },errorFields,"活动地址")

          service.executeTask(function () {
            _t.activity.registerCount = res.result.registerCount;
          },errorFields,"支持报名人数")

          service.executeTask(function () {
            _t.activity.hasCost = res.result.hasCost;
          },errorFields,"是否收费")

          service.executeTask(function () {
            if (_t.activity.hasCost === 1) {
              _t.activity.cost = res.result.cost;
            }
          },errorFields,"报名费用")

          service.executeTask(function () {
            _t.activity.urlId = res.result.urlId;
          },errorFields,"静态资源标识")

          if(errorFields.length !== 0){
            uni.showToast({
              title:'获取失败的参数 :  [  ' + errorFields.toString()  +  '  ] ',
              icon: 'none',
              duration: 2500
            })
          }
        }
      }).finally(() => {
        _t.loading.step();
      })
    },
    /* 校验参数 */
    checkParam() {
      let _t = this;
      let check = service.check;
      let data = _t.activity;
      let popup = _t.$refs.popup;
      if (check.isNull(data.title)) {
        popup.error("请填写商品标题...")
        return true
      }
      if (check.isNull(data.banner.list)) {
        popup.error("请上传背景图像...")
        return true
      }
      if (check.isNull(data.overview)) {
        popup.error("请填写活动简介...")
        return true
      }
      if (check.isNull(data.content)) {
        popup.error("请填写活动详情...")
        return true
      }
      if (check.isNull(data.time.value)) {
        popup.error("请设定活动时间...")
        return true
      }
      if (check.arrItemIsNull([data.location.lng, data.location.lat, data.location.text])) {
        popup.error("请定位活动地址")
        return true;
      }
      if (check.isNull(data.registerCount)
          || (data.registerCount !== -1 && data.registerCount < 1)) {
        popup.error("支持报名人数错误,值范围: [ -1 或 大于 0 的数值 ]")
        return true
      }
      // 如果收费校验报名费用
      if (data.hasCost === 1) {
        if (check.isNumber(data.cost)) {
          if (check.isDecimalOutBounds(data.cost, 2)) {
            popup.error("报名费用只能精确到分(只保留两位小数)")
            return true
          }
        } else {
          popup.error("报名费用必须为数字")
          return true;
        }
      }
      console.log("通过参数校验....")
      return false;
    },
    /* 获取请求参数 */
    getRequestParam() {
      let _t = this;
      let temp = service.copy(this.activity);
      let check = service.check;
      let data = {
        title: temp.title,
        overview: temp.overview,
        content: temp.content.replaceAll(_t.imgApi, ""),
        startTime: temp.time.value[0],
        endTime: temp.time.value[1],
        address: temp.location.text,
        lat: temp.location.lat,
        lng: temp.location.lng,
        registerCount: temp.registerCount,
        hasCost: temp.hasCost,
        urlId: temp.urlId,
      }
      // 背景图处理
      if (!check.isNull(temp.banner.list[0].base64)) {
        data.banner = temp.banner.list[0].base64;
      }
      // 如果收费 追加报名费用
      if (temp.hasCost === 1) {
        data.cost = temp.cost;
      }
      // 如果有id 则为修改追加id
      if (!check.isNull(temp.id)) {
        data.id = temp.id;
      }
      console.log(" requestParam : ", data)
      return data;
    }
  },
  onLoad(e) {
    // 获取图像地址前缀
    this.imgApi = this.$reqConfig.URLIMAGE
    // 获取请求头类型
    this.contentType = this.$reqConfig.CONTENTTYPE + ";+charset=UTF-8"
    // 获取token
    this.token = uni.getStorageSync("merchantsToken").token;

    // todo : 解析路由传过来的值
    console.log("路由过来的参数 : ", e)
    if (!service.check.isNull(e)) {
      if (!service.check.isNull(e.target)) {
        this.target = e.target;
        this.activity.id = e.id
      }
    }
    /* 如果当前页面目的是添加 */
    if (this.target === 'add') {
      // 活动地址 经纬度初始化为当前定位位置
      this.activity.location.cacheLat = uni.getStorageSync("dingwei").latitude
      this.activity.location.cacheLng = uni.getStorageSync("dingwei").longitude
      // 如果为空 则 重新定位
      if (service.check.arrItemIsNull([this.activity.location.cacheLat, this.activity.location.cacheLng])) {
        let t = this;
        service.getLocation(t, {
          ok: function (t, res) {
            t.activity.location.cacheLat = res.latitude;
            t.activity.location.cacheLng = res.longitude;
            uni.setStorageSync({
              key: 'dingwei',
              data: {
                longitude: res.longitude,
                latitude: res.latitude,
              },
            });
          }
        })
      }
    } else {
      uni.showLoading({
        title: '加载信息中',
        mask: true
      })
      this.loading.threshold++;
      this.getDetail();
    }
  }
}
</script>

<style>
/deep/ .uni-section__content-title.data-v-5584ec96 {
  font-size: 34 rpx !important;
}

/*标题分割线样式*/
/deep/ .line.data-v-5584ec96 {
  height: 15px;
  background-color: #0dd8ae !important;
  border-radius: 5px;
  width: 7px !important;
}

/*表单 label*/
.u-form-item__body__left__content__label.data-v-067e4733 {
  font-size: 30 rpx;
  font-weight: bold;
}

/*表单下划线*/
.u-line.data-v-727e452e {
  border-bottom-width: 8 rpx !important;
}

#editor {
  width: 100%;
  height: 300px;
  background-color: #CCCCCC;
  z-index: 1000
}
</style>
